﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Lm.Common.Web.Security
{
    public class VerificationCode
    {
        public Image CreateVerificationCodeImage(out string text)
        {
            //字符集
            var charList = "qwertyuipasdfghjkzxcvbnm23456789";
            //字符间距
            var charDistance = 13;
            //旋转角度
            var angle = 40;
            //图片大小
            var img = new Bitmap(90, 42);

            var g = Graphics.FromImage(img);
            g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            var r = new Random();
            StringBuilder randomString = new StringBuilder();
            for (int i = 0; i < 5; i++)
            { randomString.Append(charList[r.Next(charList.Length)]); }
            text = randomString.ToString();
            for (int i = 0; i < randomString.Length; i++)
            {
                var str = randomString[i].ToString();
                System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
                path.AddString(str.ToString(), new FontFamily("宋体"), (int)FontStyle.Bold, 40,
                    new PointF(charDistance * i, 0),
                    StringFormat.GenericDefault);
                var m = new System.Drawing.Drawing2D.Matrix();
                m.RotateAt(r.Next(angle) * (r.Next(2) == 1 ? -1 : 1), new PointF(charDistance * i + 16, 21));
                path.Transform(m);
                g.FillPath(Brushes.Black, path);
                m.Dispose();
                path.Dispose();
            }
            g.Dispose();
            return img;
        }
    }
}
